import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Space, Select, Upload, message } from 'antd';
import { history } from 'umi';
import type { ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import InformationModal from '@/components/InformationModal';
import styles from '../index.less';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import { DeleteOutlined } from '@ant-design/icons';
// import { Document, Page, pdfjs } from 'react-pdf';
// pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
// import jianli from require('@/assets/jianli.pdf')

const { Option } = Select;

export type Position = {
  avatar: string;
  realName: string;
  nickName: string;
  email: string;
  outUserNo: string;
  phone: string;
  permission?: string[];
};
export type inf = {
  key: number;
  name: string;
  sex: string;
  position: string;
  education: string;
  address: string;
};

const tableListDataSource: Position[] = [];

const realNames = ['马巴巴'];
const nickNames = ['巴巴'];
const emails = ['baba@antfin.com'];
const phones = ['12345678910'];
const permissions = [[]];

for (let i = 0; i < 1; i += 1) {
  tableListDataSource.push({
    outUserNo: `${102047 + i}`,
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/upvrAjAPQX/Logo_Tech%252520UI.svg',
    realName: realNames[i % 4],
    nickName: nickNames[i % 4],
    email: emails[i % 4],
    phone: phones[i % 4],
    permission: permissions[i % 4],
  });
}

const renderContent = (order: {} | null | undefined, text: {} | null | undefined) => {
  return (
    <div className={styles.content}>
      <div className={styles.top}>
        {text}：{order}
      </div>
      {text === '职位名称' ? (
        <div className={styles.bottom}>
          接收简历：{5}&nbsp; 已筛选：{'3/5'}&nbsp; 已面试：{1}&nbsp; 已发offer：{1}&nbsp; 已入职：
          {1}
        </div>
      ) : (
        <div className={styles.bottom} style={{ width: 'auto' }}>
          &nbsp;
        </div>
      )}
    </div>
  );
};

const infTable: inf[] = [];
for (let i = 0; i < 100; i++) {
  infTable.push({
    key: i,
    name: `王小明 ${i}`,
    sex: '男',
    position: 'react开发工程师',
    education: '本科',
    address: `London Park no. ${i}`,
  });
}

const DetailList: React.FC = () => {
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [modalText, setModalText] = useState('');
  const [showBtn, setShowBtn] = useState(true);
  const [showModalBtn, setShowModalBtn] = useState(true);
  const [selectList, setSelectList] = useState<number[]>([]);
  const [channelModal, setChannelModal] = useState(false);
  const [showResume, setShowResume] = useState(false);
  // const [numPages, setNumPages] = useState(null);
  // const [pageNumber, setPageNumber] = useState(1);
  // const jianli = require('@/assets/jianli.pdf')

  useEffect(() => {
    if (history.location.query && history.location.query.showBtn === 'false') {
      setShowBtn(false);
    }
  }, []);

  const handleOk = () => {
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setChannelModal(false);
      setConfirmLoading(false);
      history.push('/recruitment/information/recruitmentDetail/invitation');
    }, 1000);
  };

  const del = () => {
    if (selectList.length) {
      setModalText('您确定删除所选中的简历吗？');
      setShowModalBtn(true);
      setVisible(true);
    } else {
      setModalText('请选择至少一份简历');
      setShowModalBtn(false);
      setVisible(true);
    }
  };

  const handleChange = (value: any) => {
    console.log(`selected ${value}`);
  };

  const columns: ProColumns<Position>[] = [
    {
      dataIndex: 'nickName',
      title: '职位名称',
      width: 150,
      render: (text, record) => {
        return {
          children: renderContent(record.nickName, '职位名称'),
          props: {
            colSpan: 2,
          },
        };
      },
    },
    {
      dataIndex: 'email',
      title: '招聘负责人',
      render: (text, record) => {
        return {
          children: renderContent(record.email, '招聘负责人'),
          props: {
            colSpan: 1,
          },
        };
      },
    },
    {
      dataIndex: 'phone',
      title: 'HC',
      render: (text, record) => {
        return {
          children: renderContent(record.phone, 'HC'),
          props: {
            colSpan: 1,
          },
        };
      },
    },
    {
      dataIndex: 'role',
      title: '发布时间',
      render: (text, record) => {
        return {
          children: renderContent('2021-9-3', '发布时间'),
          props: {
            colSpan: 1,
          },
        };
      },
    },
    {
      dataIndex: 'permission',
      title: '预计停止',
      render: (text, record) => {
        return {
          children: renderContent('2021-9-10', '预计停止'),
          props: {
            colSpan: 1,
          },
        };
      },
    },
    {
      title: '操作',
      dataIndex: 'x',
      valueType: 'option',
      render: (text, record) => {
        return (
          <>
            <DeleteOutlined
              className={styles.delIcon}
              onClick={() => {
                del();
              }}
            />
            {showBtn && (
              <>
                <Button
                  type="primary"
                  className={styles.btn}
                  size="small"
                  ghost
                  onClick={() => {
                    setChannelModal(true);
                  }}
                >
                  上传简历
                </Button>
                <Button type="primary" className={styles.btn} size="small" onClick={() => {}}>
                  全部推送
                </Button>
                <Button type="primary" className={styles.btn} size="small">
                  全部简历
                </Button>
                <Button
                  className={styles.btn}
                  style={{ color: '#EA7F00', borderColor: '#EA7F00' }}
                  size="small"
                >
                  过滤简历
                </Button>
              </>
            )}
          </>
        );
      },
    },
  ];
  const infTabelcolumns: ProColumns<inf>[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      //   width: 140,
      render: (text, record) => {
        return `姓名：${text}`;
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      fixed: 'left',
      width: 100,
      render: (text, record) => {
        return `性别：${text}`;
      },
    },
    {
      title: '期望职位',
      dataIndex: 'position',
      key: 'position',
      fixed: 'left',
      render: (text, record) => {
        return `期望职位：${text}`;
      },
    },
    {
      title: '学历',
      dataIndex: 'education',
      key: 'education',
      fixed: 'left',
      width: 100,
      render: (text, record) => {
        return `学历：${text}`;
      },
    },
    {
      title: '毕业院校',
      dataIndex: 'address',
      key: 'address',
      fixed: 'left',
      render: (text, record) => {
        return `毕业院校：${text}`;
      },
    },
    {
      title: 'Action',
      key: 'operation',
      fixed: 'left',
      render: () => (
        <Button
          type="link"
          onClick={() => {
            setShowResume(true);
          }}
        >
          查看详情
        </Button>
      ),
    },
    {
      title: '操作',
      dataIndex: 'x',
      valueType: 'option',
      fixed: 'right',
      render: (text, record) => {
        return (
          <>
            {showBtn && (
              <>
                <Button
                  type="primary"
                  className={styles.btn}
                  size="small"
                  //   onClick={() => {
                  //     history.push('/recruitment/information/positionDetail');
                  //   }}
                >
                  推送
                </Button>
                <Button
                  type="primary"
                  className={styles.btn}
                  size="small"
                  onClick={() => {
                    setModalText('确认发送面试邀约吗？');
                    // setModalText('已通知HR，请等待面试邀约通知')
                    setShowModalBtn(true);
                    setVisible(true);
                  }}
                >
                  面试邀约
                </Button>
              </>
            )}
            <Button type="primary" ghost className={styles.btn} size="small" onClick={() => {}}>
              备注
            </Button>
          </>
        );
      },
    },
  ];

  const props = {
    name: 'file',
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info: any) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
  };

  // function onDocumentLoadSuccess({ numPages }) {
  //   setNumPages(numPages);
  // }

  return (
    <PageHeaderWrapper>
      <ProCard headerBordered direction="column">
        <ProTable<Position>
          columns={columns}
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            console.log(params, sorter, filter);
            return Promise.resolve({
              data: tableListDataSource,
              success: true,
            });
          }}
          pagination={false}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }}
          tableAlertRender={false}
          rowKey="outUserNo"
          showHeader={false}
          headerTitle=""
          toolBarRender={false}
          search={false}
        />
        <ProTable<inf>
          columns={infTabelcolumns}
          style={{ paddingLeft: '40px' }}
          rowClassName={(record, index) => (index === 0 ? styles.blue : '')}
          
          request={(params, sorter, filter) => {
            // 表单搜索项会从 params 传入，传递给后端接口。
            console.log(params, sorter, filter);
            return Promise.resolve({
              data: infTable,
              success: true,
            });
          }}
          rowSelection={{
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectList(JSON.parse(JSON.stringify(selectedRowKeys)));
              console.log(selectedRowKeys, selectedRows);
            },
          }}
          rowKey="key"
          pagination={{
            showQuickJumper: true,
          }}
          showHeader={false}
          toolBarRender={false}
          search={false}
        />
        <InformationModal
          visible={visible}
          modalText={modalText}
          confirmLoading={confirmLoading}
          handleOk={() => handleOk()}
          onCancel={() => setVisible(false)}
          showModalBtn={showModalBtn}
        />
        <Modal
          visible={channelModal}
          centered
          width={500}
          footer={false}
          bodyStyle={{ textAlign: 'left', paddingTop: '67px' }}
          onCancel={() => setChannelModal(false)}
        >
          <p style={{ textAlign: 'left', paddingLeft: '76px' }}>渠道来源选择</p>
          <Select
            defaultValue="lucy"
            style={{ width: '340px', paddingLeft: '76px' }}
            onChange={handleChange}
          >
            <Option value="jack">BOSS</Option>
            <Option value="lucy">前程无忧</Option>
            <Option value="disabled">智联招聘</Option>
            <Option value="Yiminghe">猎聘</Option>
          </Select>
          <div style={{ textAlign: 'center', margin: '54px', marginBottom: '20px' }}>
            <Space>
              <Upload {...props} maxCount={1} showUploadList={false}>
                <Button type="primary">确定</Button>
              </Upload>
              <Button htmlType="button" onClick={() => setChannelModal(false)} size="middle">
                取消
              </Button>
            </Space>
          </div>
        </Modal>
        <Modal
          visible={showResume}
          footer={false}
          onCancel={() => {
            setShowResume(false);
          }}
        >
          {/* <Document file={jianli} onLoadSuccess={onDocumentLoadSuccess}>
            <Page pageNumber={pageNumber} />
          </Document> */}
          <p>
            {/* Page {pageNumber} of {numPages} */}
            123123
          </p>
        </Modal>
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default DetailList;
